package com.morn.fanfou.fragment;

import java.io.File;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.MediaStore;
import android.provider.MediaStore.MediaColumns;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.morn.fanfou.R;

import com.morn.fanfou.ConversationActivity;
import com.morn.fanfou.util.BitmapUtil;

public class UpdateFragment extends Fragment implements OnClickListener {

	private EditText textView;

	private ImageView imageView;

	private View clearView;

	private ImageView cameraView;

	private ImageView galleryView;

	private TextView countView;

	private Bitmap myBitmap;

	private File imageFile;

	private AlertDialog dialog;

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View v = inflater.inflate(R.layout.update, container, false);
		findView(v);

		return v;
	}

	private void findView(View v) {
		TextView titleText = (TextView) v.findViewById(R.id.header_title_text);
		titleText.setText(R.string.header_title_send_status);
		ImageView leftImage = (ImageView) v
				.findViewById(R.id.header_image_left);
		leftImage.setOnClickListener(this);

		ImageView rightImage = (ImageView) v
				.findViewById(R.id.header_image_right);
		rightImage.setImageResource(R.drawable.ic_menu_upload);
		rightImage.setOnClickListener(this);

		textView = (EditText) v.findViewById(R.id.update_send_text);

		imageView = (ImageView) v.findViewById(R.id.update_send_image);
		imageView.setOnClickListener(this);

		clearView = v.findViewById(R.id.update_send_clear);
		clearView.setOnClickListener(this);

		cameraView = (ImageView) v.findViewById(R.id.update_send_camera);
		cameraView.setOnClickListener(this);

		galleryView = (ImageView) v.findViewById(R.id.update_send_gallery);
		galleryView.setOnClickListener(this);

		countView = (TextView) v.findViewById(R.id.update_send_count);

		textView.addTextChangedListener(new ConversationActivity.MyTextWatcher(
				this.getActivity(), countView));
		dialog = new AlertDialog.Builder(this.getActivity())
				.setTitle(R.string.notice)
				.setMessage(R.string.clear_text)
				.setPositiveButton(R.string.ok,
						new AlertDialog.OnClickListener() {
							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								textView.setText("");
							}
						})
				.setNegativeButton(R.string.cancel,
						new AlertDialog.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								dialog.cancel();
							}
						}).create();

	}

	@Override
	public void onActivityResult(int requestCode, int resultCode, Intent data) {
		if (resultCode == Activity.RESULT_OK && data != null) {
			if (myBitmap != null) {
				myBitmap.recycle();
			}
			if (requestCode == 0) {
				Uri imageUri = data.getData();
				disposeUri(imageUri);
			} else if (requestCode == 1) {
				String[] items = { BaseColumns._ID, MediaColumns.DATA };
				Cursor cursor = this.getActivity().managedQuery(
						MediaStore.Images.Media.EXTERNAL_CONTENT_URI, items,
						null, null, BaseColumns._ID + " desc");
				String latestImage = "";
				if (cursor != null && cursor.getCount() > 0) {
					cursor.moveToFirst();
					for (cursor.moveToFirst(); !cursor.isAfterLast();) {
						latestImage = cursor.getString(1);
						imageFile = new File(latestImage);
						myBitmap = BitmapUtil.compressBitmap(imageFile, 200,
								200);

						break;
					}
				}
				if (myBitmap != null) {
					imageView.setImageBitmap(myBitmap);
				}
				Log.i("UpdateActivity", "latestImage=" + latestImage);
			} else if (requestCode == 2) {
				String name = data.getStringExtra("name");
				int cursor = textView.getSelectionStart();
				textView.getText().insert(cursor, name + " ");
			}

		}

	}

	private void disposeUri(Uri imageUri) {
		imageFile = getFile(imageUri);
		// ContentResolver resolver = getContentResolver();
		// in = resolver.openInputStream(imageUri);
		// myBitmap = BitmapFactory.decodeStream(in);
		myBitmap = BitmapUtil.compressBitmap(imageFile, 200, 200);
		imageView.setImageBitmap(myBitmap);

	}

	@Override
	public void onClick(View v) {
		int viewId = v.getId();
		if (viewId == R.id.update_send_image) {
			imageFile = null;
			imageView.setImageBitmap(null);
		} else if (viewId == R.id.update_send_camera) {
			startCameraActivity();
		} else if (viewId == R.id.update_send_gallery) {
			startGalleryActivity();
		} else if (viewId == R.id.update_send_clear) {
			if (textView.length() > 0) {
				dialog.show();
			}
		} else if (viewId == R.id.header_image_right) {
			update();
		} else if (viewId == R.id.header_image_left) {
			this.getActivity().finish();
		}

	}

	private void startCameraActivity() {
		Intent getImageByCamera = new Intent(
				"android.media.action.IMAGE_CAPTURE");
		// Uri photoUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
		// getImageByCamera.putExtra(MediaStore.EXTRA_OUTPUT, photoUri);
		this.getActivity().startActivityForResult(getImageByCamera, 1);
	}

	private void startGalleryActivity() {
		Intent getImage = new Intent(Intent.ACTION_GET_CONTENT);
		getImage.addCategory(Intent.CATEGORY_OPENABLE);
		getImage.setType("image/*");
		this.getActivity().startActivityForResult(getImage, 0);
	}

	private void update() {
		
	}

	public File getFile(Uri uri) {

		String[] proj = { MediaColumns.DATA };

		Cursor actualimagecursor = this.getActivity().managedQuery(uri, proj,
				null, null, null);

		int actual_image_column_index = actualimagecursor
				.getColumnIndexOrThrow(MediaColumns.DATA);

		actualimagecursor.moveToFirst();

		return new File(actualimagecursor.getString(actual_image_column_index));
	}
}
